package ae.pcfc.etks.online.ced.web.web.util;

import java.io.Serializable;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ae.pcfc.etks.online.ced.web.domain.AuditableEntity;


public class SaveOrUpdateAuditLogListener extends EmptyInterceptor{

	private static Logger log = LoggerFactory.getLogger(SaveOrUpdateAuditLogListener.class);

	public boolean onFlushDirty(Object entity,Serializable id,Object[] currentState,Object[] previousState, String[] propertyNames, 
			Type[] types) {
		if(entity instanceof AuditableEntity){
			setPreviousValue(currentState, propertyNames, "createdBy", previousState);
			setPreviousValue(currentState, propertyNames, "whenCreated", previousState);
			setValue(currentState, propertyNames, "lastUpdatedBy", UtilCommon.getLoggedInUserName());
			setValue(currentState, propertyNames, "lastUpdated", UtilCommon.getCurrentDate());
			return true;
		}
		return false;
	}

	public boolean onSave(Object entity,Serializable id,Object[] state,String[] propertyNames,Type[] types) {
		if(entity instanceof AuditableEntity){
			setValue(state, propertyNames, "createdBy", UtilCommon.getLoggedInUserName());
			setValue(state, propertyNames, "whenCreated", UtilCommon.getCurrentDate());
			return true;
		}
		return false;
	}
	
	
	private void setValue(Object[] currentState, String[] propertyNames, String propertyToSet, Object value) {
		for(int i=0;i<propertyNames.length;i++){
			if(propertyToSet.equals(propertyNames[i])){
				currentState[i] = value;
				break;
			}
		}
	}
	
	private void setPreviousValue(Object[] currentState, String[] propertyNames, String propertyToSet, Object[] previousState) {
		if(previousState == null)
			return;
		for(int i=0;i<propertyNames.length;i++){
			if(propertyToSet.equals(propertyNames[i])){
				currentState[i] = previousState[i];
				break;
			}
		}
	}
	
}
